#include "datafile.h"

#if debug
#include <stdio.h>
#endif

datafile_c::datafile_c(const char * aPfad, const char * aFile)
{
  char httpdef[] = "http://";
  http = new char[8];
  memcpy(http,httpdef,7);
  http[7] = 0;
  changed = false;
  fName = new char[strlen(aPfad)+strlen(aFile)+1];
  memcpy(fName,aPfad,strlen(aPfad)+1);
  memcpy(fName+strlen(aPfad),aFile,strlen(aFile)+1);
  htmlfile = new char[2];
  htmlfile[0] = 0;
  load();
}

datafile_c::~datafile_c()
{
//  delete fName;
//  if (strlen(http)>5) {delete http;}
}

int datafile_c::setHTTP(char * text) {
  if (strcmp(text,http) != 0) {
    delete http;
    http = new char[strlen(text)+1];
    memcpy(http,text,strlen(text));
    http[strlen(text)] = 0;
    changed = true;
    delete text;
  }
  return 0;
}

int datafile_c::setFile(char * text) {
  if (strcmp(text,htmlfile) != 0) {
//    if (strlen(htmlfile)>5) {delete htmlfile;}
    htmlfile = new char[strlen(text)+1];
    memcpy(htmlfile,text,strlen(text));
    htmlfile[strlen(text)] = 0;
    changed = true;
    delete text;
  }
  return 0;
}

char * datafile_c::getHttp() {
  return http;
}

char * datafile_c::getFile() {
  return htmlfile;
}

int datafile_c::checkSave() {
  if (changed) {
    if (OpenWriteXMLFile(fName)) {
      char OpenData[] = "Data";
      OpenXMLGroup(OpenData);
      char OpenEntry[] = "Entry";
      OpenXMLGroup(OpenEntry);
      char aHttp[] = "Http";
      WriteStringXML(aHttp,http);
      char aFile[] = "File";
      WriteStringXML(aFile,htmlfile);
      CloseWriteXMLFile();
    }
  }
  return 0;
}

int datafile_c::load() {
  if (OpenReadXMLFile(fName)) {
    while (getXMLTag()) {
      if (strcmp(TagName,"Data") == 0) {
        loadData();
      } else if (strcmp(TagName,"/Data") == 0) {
        CloseXMLFile();
        return 0;
      }
    }
    CloseXMLFile();
  }
  return 0;
}

int datafile_c::loadData() {
  while (getXMLTag()) {
    if (strcmp(TagName,"Entry") == 0) {
      loadEntry();
    } else if (strcmp(TagName,"/Data") == 0) {
      return 0;
    }
  }
  return 0;
}

int datafile_c::loadEntry() {
  while (getXMLTag()) {
    if (strcmp(TagName,"Http") == 0) {
      delete http;
      http = new char[strlen(TagString)+1];
      memcpy(http,TagString,strlen(TagString));
      http[strlen(TagString)] = 0;
      getXMLTag();
    } else if (strcmp(TagName,"File") == 0) {
      delete htmlfile;
      htmlfile = new char[strlen(TagString)+1];
      memcpy(htmlfile,TagString,strlen(TagString));
      htmlfile[strlen(TagString)] = 0;
      getXMLTag();
    } else if (strcmp(TagName,"/Entry") == 0) {
      return 0;
    }
  }
  return 0;
}

